package com.innovation.ic.cyz.base.handler;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Component
public class PageHandler extends AbstractHandler {

    /**
     * @return
     * @description list转换方法
     * @parms
     * @author Mr.myq
     * @datetime 2022/8/5 下午4:06
     */
    public static <T> PageInfo<T> convertPage(List<?> source, Class<T> targetClazz) {
        PageInfo<T> ts = null;
        try {
            if(CollectionUtils.isEmpty(source))
                return new PageInfo<>(Collections.emptyList());
            //获取分页总数
            PageInfo<?> pageInfo = new PageInfo<>(source);
            List<T> tList = new ArrayList<>(source.size());
            for (Object obj : source) {
                T t = targetClazz.newInstance();
                BeanUtils.copyProperties(obj, t);
                tList.add(t);
            }
            ts = new PageInfo<T>(tList);
            ts.setTotal(pageInfo.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("convertPage<T>转换异常：", e);
            throw new RuntimeException("convertPage<T>转换异常");
        }
        return ts;
    }
}
